package com.upload.spring.boot.server;


import com.qiniu.common.QiniuException;
import com.qiniu.common.Region;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.upload.spring.boot.properties.QiNiuProperties;
import com.upload.spring.boot.properties.QiNiuTokenInMemory;
import com.upload.spring.boot.type.UploadType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <pre>
 * 七牛对象存储服务
 * </pre>
 * 
 * <small> 2018年4月6日 | Aron</small>
 */
public class QiNiuUploadServer implements UploadCustomizer {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private UploadManager uploadManager;
    private Configuration cfg;
    private QiNiuProperties config;
    private QiNiuTokenInMemory qiNiuToken;


    public QiNiuUploadServer(QiNiuProperties config,QiNiuTokenInMemory qiNiuToken) {
        cfg = new Configuration(Region.autoRegion());
        uploadManager = new UploadManager(cfg);
        this.config = config;
        this.qiNiuToken = qiNiuToken;
    }

    @Override
    public UploadType getUploadType() {
        return UploadType.QINIU;
    }

    @Override
    public String upload(byte[] bytes, String fileName) {
        String token = qiNiuToken.get();

        try {
            uploadManager.put(bytes, fileName, token);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        String fileURL = this.config.getAccessURL() + fileName;
            log.info("上传成功，url:{}", fileURL);
            return fileURL;

    }

}
